import {PageContainer, ProFormInstance} from '@ant-design/pro-components';

import {
  getInterfaceInfoByIdUsingGet,
  invokeInterfaceInfoUsingPost,
} from '@/services/api-backend/interfaceInfoController';
import {history, useModel, useParams} from '@@/exports';
import {
  Badge,
  Card,
  Collapse,
  Descriptions,
  Divider,
  Flex,
  Form,
  GetProps,
  Input,
  message,
  Statistic,
  Table,
  TableProps,
  Tabs,
  Tag,
  Tooltip
} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import Icon, {CopyTwoTone, HeartOutlined} from '@ant-design/icons';
import ParamsTable from "@/components/ParamsTable/ParamsTable";
import JsonView from '@uiw/react-json-view';
import {githubLightTheme} from '@uiw/react-json-view/githubLight';
import style from "./index.less"
import {listInterfaceInfoLogHistoryByIdUsingGet} from "@/services/api-backend/interfaceInfoLogController";
import moment from "moment";
import ThrottledButton from "@/components/ThrottledButton";
import FastTest from "@/pages/InterfaceInfo/components/FastTest";
import {Favorite} from "@/components/Favorite";
import {toggleFavoriteUsingPost} from "@/services/api-backend/recommendController";



const badgeRibbon: React.CSSProperties = {
  width: 65,
  height: 30,
  textAlign: "center",
  fontSize: 16,
  lineHeight: 1.7,
}
const fastTestSuccess: React.CSSProperties = {
  width: "100%",
  borderWidth: "1px 1px 1px 5px",
  padding: 15,
  borderColor: "#eee",
  borderStyle: "solid",
  borderLeftColor: "#5cb85c",
  margin: "0 0 1rem",
  borderRadius: 3,
  display: "flex",
  alignItems: "center", // 垂直居中对齐
  justifyContent: "flex-start", // 横向左对齐
  marginBottom: 30
}


interface HistoryDataType {
  code: string;
  count: string;
  lastTime: number;
  time: string;
}


/**
 * 主页
 * @constructor
 */
const InterfaceInfoIndex: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<API.InterfaceInfo>();
  const [totalNum, setTotalNum] = useState<number>();
  //存储结果变量
  const [invokeRes, setInvokeRes] = useState<any>();
  //调用加载状态变量，默认为false
  const [invokeLoading, setInvokeLoading] = useState(false);
  const [fastTest, setFastTest] = useState(false);
  const [fastTestSpining, setFastTestSpining] = useState(false);
  const [paramsJson, setParamsJson] = useState({})
  const [historyData, setHistoryData] = useState<API.InterfaceInfoLogListVo>()
  const formRef = useRef<ProFormInstance>();
  const [form] = Form.useForm();
  const [fastTestCode, setFastTestCode] = useState()
  const [dataLoaded, setDataLoaded] = useState<boolean>(false);
  // 使用 useParams 钩子函数获取动态路由参数
  const params = useParams();
  const {location} = history;
  //获取当前登录信息
  const {initialState} = useModel('@@initialState');
  const loadData = async () => {
    if (!params.id) {
      message.error('参数不存在');
      return;
    }
    setLoading(true);
    try {
      const res = await getInterfaceInfoByIdUsingGet({
        id: params.id,
      });
      setData(res.data);
      setTotalNum(res.data.totalNum)
      if (res?.data?.requestParams) {
        const requestParamsJson = JSON.parse(res?.data?.requestParams)
        const rpJson = Object.keys(requestParamsJson).reduce((acc, item) => {
          if (item) {
            acc[item] = "";
          }
          return acc;
        }, {})
        setParamsJson(JSON.stringify(rpJson, null, 2))
        formRef.current?.setFieldsValue({
          // 使用 JSON.stringify 格式化 JSON 对象
          // 参数 2 表示缩进两个空格
          userRequestParams: JSON.stringify(rpJson, null, 2)
        })
      }
    } catch (error) {
      message.error('删除失败.' + error.message);
    }
    setLoading(false);
  };
  const invokeInterfaceCount = async () => {

  }

  /**
   * 收藏/取消收藏
   * @param liked
   */
  const toggleFavorite=async (liked:boolean)=>{
    try {
      const userId=initialState?.loginUser?.id
      const interfaceId=data?.id
      const enable=liked;
      const  {data:response}= await  toggleFavoriteUsingPost({
        userId,
        interfaceId,
        enable
      })
      if(response){
        message.success(liked?"收藏成功":"取消收藏成功")
      }
    }catch (e){
        message.error(liked?"收藏失败":"取消收藏失败，",e)
    }
  }

  const loadHistoryData = async () => {
    try {
      const res = await listInterfaceInfoLogHistoryByIdUsingGet({
        interfaceInfoId: params.id
      })
      if (res?.data) {
        setHistoryData(res?.data)
      }
    } catch (e) {
      message.error('历史数据获取失败.' + e.message);
    }
  }

  useEffect(() => {
    const loadAllData = async () => {
      await loadData();
      await loadHistoryData();
      setDataLoaded(true) // 标记数据加载完成
    };
    loadAllData();
  }, []);
  useEffect(() => {
    if (dataLoaded && location.pathname.includes('/one/interface_info')) {
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      fastTestSubmit()
    }
  }, [dataLoaded]);

  const onFinish = async (values: any, load = true) => {
    if (!params.id) {
      message.error('参数不存在');
      return;
    }
    setInvokeLoading(true);
    try {
      const res = await invokeInterfaceInfoUsingPost({
        id: params.id,
        ...values,
      });
      // const tmpTotalNum = invokeInterfaceCount()
      // const tmpData = res
      if (res && res.code === 0) {
        setInvokeRes(res.data)
        message.success('请求成功');
      } else {
        setInvokeRes(res.message);
        // message.error(tmpData.message);
      }
    } catch (error: any) {
      message.error('操作失败，' + error.message);
    }
    setInvokeLoading(false);
  };
  const fastTestSubmit = async () => {
    setFastTestSpining(true)
    try {
      const res = await invokeInterfaceInfoUsingPost({
        id: params.id,
        userRequestParams: data?.requestParams
      })
      setFastTestCode(res.code)
    } catch (error: any) {
      message.error('操作失败，' + error.message);
    }
    setTimeout(() => {
      setFastTest(true)
      setFastTestSpining(false)
    }, 2000)
  }
  const genExtra = () => (
    <CopyTwoTone
      onClick={(event) => {
        navigator.clipboard.writeText(data?.result)
        message.success("复制成功")
        event.stopPropagation();
      }}
    />
  );

  const historyAnaylsisColumns: TableProps<HistoryDataType>['columns'] = [
    {
      title: '状态码',
      dataIndex: 'code',
      key: 'code',
      align: "center",
      render: (_, record) => [
        record.code == 200 ? <p style={{color: "#5cb85c", margin: 0}}>正常</p> :
          <p style={{color: "#ff0b1e", margin: 0}}>故障</p>
      ]
    },
    {
      title: '累加次数',
      dataIndex: 'accNum',
      key: 'accNum',
      align: "center"
    },
    {
      title: '最后检测时间',
      dataIndex: 'lastTime',
      key: 'lastTime',
      valueType: 'dateTime',
      align: "center",
      render: (_, record) => [
        <p style={{margin: 0}}>{moment(record.lastTime).format('YYYY-MM-DD HH:mm:ss')}</p>
      ]
    }
  ];

  const historyListColumns: TableProps<HistoryDataType>['columns'] = [
    {
      title: '状态码',
      dataIndex: 'code',
      key: 'code',
      align: "center",
      render: (_, record) => [
        record.code == 200 ? <p style={{color: "#5cb85c", margin: 0}}>正常</p> :
          <p style={{color: "#ff0b1e", margin: 0}}>故障</p>
      ]

    },
    {
      title: '最后检测时间',
      dataIndex: 'lastTime',
      key: 'lastTime',
      valueType: 'dateTime',
      align: "center",
      render: (_, record) => [
        <p style={{margin: 0}}>{moment(record.lastTime).format('YYYY-MM-DD HH:mm:ss')}</p>
      ]
    }
  ];

  const options = [
    {label: 'Apple', value: 'Apple'},
    {label: 'Pear', value: 'Pear'},
    {label: 'Orange', value: 'Orange'},
  ];
  return (
    <PageContainer title={'查看接口文档'}>


      <Badge.Ribbon text={data?.free===0?"免费":"付费"} color={data?.free===0?"green":"purple"} style={badgeRibbon}>
        <Card>
          {data ? (
            <>
              <Flex gap="middle" justify={"space-between"}>
                <Descriptions title={
                  <>
                    <Flex align={"center"}>
                      <div className="ellipsis-text ellipsis-text-2"><strong style={{color: "#014CC1"}}>API简介：</strong>
                        <Tooltip placement="topLeft" title={data.description}>
                          {data.description}
                        </Tooltip>
                      </div>
                      <div style={{marginTop:4}}>
                        <Favorite defaultLiked={data?.liked==1} onLikeChange={toggleFavorite} size={22}/></div>
                    </Flex>
                  </>}
                   column={1}>

                  {/*<Descriptions.Item label="接口状态"><Tag color="#f50">{data.status ? '开启' : '关闭'}</Tag></Descriptions.Item>*/}

                  <Descriptions.Item label="接口名称" >

                    <Tag color="#f50">{data.name}</Tag>


                  </Descriptions.Item>

                  <Descriptions.Item label="请求地址"><Tag color="#f50">
                    {data.host + data.url}
                    {/*http://localhost:8100{data.url}*/}
                  </Tag> <CopyTwoTone
                    onClick={() => {
                      navigator.clipboard.writeText(data?.host + data?.url)
                      message.success("复制成功")
                    }} style={{marginLeft: 10}}/></Descriptions.Item>
                  <Descriptions.Item label="请求方法"><Tag color="#f50">{data.method}</Tag></Descriptions.Item>
                  <Descriptions.Item label="请求参数">{data.requestParams &&
                    <JsonView collapsed={true} value={JSON.parse(data.requestParams)}
                              style={githubLightTheme}/>}</Descriptions.Item>
                  <Descriptions.Item label="请求头"><JsonView collapsed={true}
                                                              value={JSON.parse(data.requestHeader)}
                                                              style={githubLightTheme}/></Descriptions.Item>
                  <Descriptions.Item label="响应头"><JsonView collapsed={true}
                                                              value={JSON.parse(data.responseHeader)}
                                                              style={githubLightTheme}/></Descriptions.Item>
                  <Descriptions.Item label="返回格式"><Tag color="#f50">{data.resultType}</Tag></Descriptions.Item>
                  <Descriptions.Item label="创建时间"><Tag
                    color="#f50">{new Date(data.createTime).toLocaleString()}</Tag></Descriptions.Item>
                  {
                    totalNum ?
                    <Descriptions.Item className={style.antDescriptionsRow} label="剩余调用次数"><Statistic
                      value={totalNum}/></Descriptions.Item>:<Descriptions.Item  className={style.antDescriptionsRow} label="剩余调用次数" value={0}></Descriptions.Item>
                  }


                </Descriptions>
                {/*todo 可扩展API接口图片*/}
                {/*<div style={{marginRight: 54}}>*/}
                {/*  <Radio.Group block options={options} defaultValue="Pear" optionType="button"/>*/}
                {/*</div>*/}


              </Flex>
              <div style={{marginTop: 14}}></div>
              {/*测试 历史统计和列表 Tabs*/}
              <div style={{
                padding: 16,
                boxShadow: "0 8px 16px -4px #2c2d300c",
                border: "3px solid #f1f3f8",
                borderRadius: 12
              }}>
                <Tabs defaultActiveKey="fastTest" items={[
                  {
                    label: `极速测试(自动)`,
                    key: "fastTest",
                    children: <>
                      {
                        location.pathname.includes('/one/interface_info') && (
                          <FastTest fastTestSpining={fastTestSpining} fastTest={fastTest}
                                    fastTestCode={fastTestCode} fastTestSuccess={fastTestSuccess}
                                    onSubmit={fastTestSubmit}/>
                        )
                      }
                    </>
                  },
                  {
                    label: `历史统计`,
                    key: "historyAnaylsis",
                    children: <>
                      <Table<HistoryDataType>
                        borderColor={"red"}
                        columns={historyAnaylsisColumns}
                        style={{marginBottom: 30, marginTop: 20}}
                        dataSource={
                          historyData?.interfaceInfoAnaylsisVos
                        }
                        bordered
                        pagination={false}
                      />
                    </>,
                  },
                  {
                    label: `历史列表`,
                    key: "historyList",
                    children: <>
                      <p style={{
                        marginTop: 20,
                        color: "rgba(60, 60, 67, 0.6)",
                        textAlign: "center",
                        fontSize: 20,
                        fontWeight: 400
                      }}>仅展示最近10条数据</p>
                      <Table<HistoryDataType>
                        borderColor={"red"}
                        columns={
                          historyListColumns
                        }
                        style={{marginBottom: 30}}
                        dataSource={
                          historyData?.interfaceInfoCodeVos
                        }
                        bordered
                        pagination={false}
                      />
                    </>,
                  },
                ]}

                />
              </div>
            </>
          ) : (
            <>接口不存在</>
          )}
        </Card>
      </Badge.Ribbon>
      <Divider/>

      <Card title={"在线测试"}>
        {/*返回示例*/}
        <Collapse
          defaultActiveKey={['collapse']}
          // onChange={onChange}
          // expandIconPosition={expandIconPosition}
          items={[
            {
              key: 'collapse',
              label: '返回示例',
              children: <div>{
                data?.result && <JsonView value={JSON.parse(data?.result)}/>
              }</div>,
              extra: genExtra(),
            },
          ]}
        />
        <Divider/>
        <Tabs
          defaultActiveKey="row"
          centered
          items={
            [
              {
                label: `row参数`,
                key: "row",
                children: <>
                  <Form name="basic" form={form} ref={formRef} layout="vertical" onFinish={onFinish}>
                    <Form.Item label="请求参数" name="userRequestParams"
                               rules={[
                                 {
                                   required: true,
                                   message: '请输入请求参数',
                                 },
                                 {whitespace: true},
                                 {
                                   validator: (_, value) => {
                                     try {
                                       JSON.parse(value);
                                       return Promise.resolve();
                                     } catch (e) {
                                       return Promise.reject(new Error('请求参数格式必须是json'));
                                     }
                                   },
                                 }
                               ]}
                    >

                      {/*<JsonViewEditor/>*/}
                      <Input.TextArea autoSize={true}/>
                      {/*<JsonView*/}
                      {/*  value={paramsJson}  // 显示的 JSON 数据*/}
                      {/*  editable={true}  // 启用编辑功能*/}
                      {/*  onChange={(value) => onJsonChange(value)}  // 处理编辑后的数据*/}
                      {/*/>*/}
                    </Form.Item>

                    <Form.Item wrapperCol={{span: 16}}>
                      {/*<Button type="primary" htmlType="submit">*/}
                      {/*  调用*/}
                      {/*</Button>*/}
                      <ThrottledButton form={form} title={"调用"}></ThrottledButton>
                    </Form.Item>
                  </Form>
                </>,
              },
              {
                label: `form-data参数`,
                key: "form-data",
                children: <ParamsTable requestParams={data?.requestParams ?? {}} onSubmitData={onFinish}/>,
              },

            ]
          }
        />


      </Card>
      <Divider/>
      <Card title="返回结果" loading={invokeLoading}>
        {
          invokeRes
        }
      </Card>

    </PageContainer>
  );
};

export default InterfaceInfoIndex;
